package com.djz.stuinfomge.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	// 网站根目录下的内容不进行过滤,还有登录页
	public static String[] excludeResourcesFileName = { "ckeditor","css","ext","images","imgs","jquery-ui","js","My97DatePicker","404.html","login/page","login/doLogin" };
	public static String[] excludeResourcesFullPath;
	public String basePath;
	//just for test
	//private int count;
	public void destroy() {

	}

	public void doFilter(ServletRequest servReq, ServletResponse servResp,
			FilterChain chain) throws IOException, ServletException {
		//System.out.println("login filter");
		//count++;
	//	System.out.println("count: "+ count);
	//	if(count ==15)
	//		System.exit(0);
		HttpServletRequest req = (HttpServletRequest) servReq;
		// 初次访问时处理，处理一次就够了
		if (basePath == null) {
			String serverName =  req.getServerName();
			//为方便fidder调试，改为计算机名
			//serverName = "lenovo-3a955f7c";
			basePath = req.getScheme() + "://" + serverName+ ":"
					+ req.getServerPort() + req.getContextPath();
			buildRootDirResourcesFullPath();
		}
		String url = req.getRequestURL().toString();
		System.out.println("url: " + url);
		// 如果不是网站根目录下的内容，则要进行登录验证
		//System.out.println("matchProcess(url): "+matchProcess(url));
		if (!matchProcess(url)) {
			
			// 通过验证，继续访问资源
			if (loginValidate(req))
				chain.doFilter(servReq, servResp);
			else {// 跳转到登录页
				HttpServletResponse resp = (HttpServletResponse) servResp;
				resp.sendRedirect(basePath + "/login/page");
				//return;
			}
		}

		else{
			//System.out.println("here123");
			chain.doFilter(servReq, servResp);
		}
		
		
	}

	private boolean loginValidate(HttpServletRequest req) {
		HttpSession session = req.getSession();
		Object currUser = session.getAttribute("currUser");
		if (currUser != null)
			return true;
		return false;
	}

	private void buildRootDirResourcesFullPath() {
		int len = excludeResourcesFileName.length;
		excludeResourcesFullPath = new String[len];
		for (int i = 0; i < len; i++){
			excludeResourcesFullPath[i] = basePath + '/'
					+ excludeResourcesFileName[i];
			//System.out.println();
		}
	}

	private boolean matchProcess(String url) {
		
		boolean match = false;
		for (int i = 0; i < excludeResourcesFullPath.length; i++){
			//System.out.println("excludeResourcesFullPath[]: "+excludeResourcesFullPath[i]);
			if (url.indexOf(excludeResourcesFullPath[i]) != -1)
				match = true;
		}
		return match;
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
